package com.pf.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * 生成图形验证码
 */
@Slf4j
public class ImgVc {

    public static void main(String[] args) {
        ImgVc imgVc = new ImgVc(180, 50, 4, 80);
        String code = imgVc.getCode();
        System.out.println("code=" + code);
        String base64 = imgVc.writeToBase64();
        System.out.println(base64);
    }

    /**
     * 验证码
     */
    private static String code = null;
    /**
     * 图片宽度
     */
    private int width;
    /**
     * 图片高度
     */
    private int height;
    /**
     * 验证码字符个数
     */
    private int codeCount;
    /**
     * 验证码干扰线数
     */
    private int lineCount;
    /**
     * 验证码图片Buffer
     */
    private BufferedImage bufferedImage = null;

    private char[] codeSequence = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
    };

    /**
     * 随机数生成器
     */
    private static SecureRandom random = new SecureRandom();

    /**
     * 生成图形验证码
     *
     * @param width     图片宽度
     * @param height    图片高度
     * @param codeCount 字符个数
     * @param lineCount 干扰线条数
     */
    public ImgVc(int width, int height, int codeCount, int lineCount) {
        this.width = width;
        this.height = height;
        this.codeCount = codeCount;
        this.lineCount = lineCount;
        this.createCode();
    }

    private void createCode() {
        int x, fontHeight, codeY, red, green, blue;
        // 每个字符的宽度
        x = width / (codeCount + 2);
        // 字体的高度
        fontHeight = height - 2;
        codeY = height - 4;

        // 图像buffer
        bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        // 生成随机数
        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        // 创建字体
        Font font = new Font("Arial", Font.PLAIN, fontHeight);
        g.setFont(font);

        for (int i = 0; i < lineCount; i++) {
            int xs = random.nextInt(width);
            int ys = random.nextInt(height);
            int xe = xs + random.nextInt(width / 8);
            int ye = ys + random.nextInt(height / 8);
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            g.setColor(new Color(red, green, blue));
            g.drawLine(xs, ys, xe, ye);
        }

        // randomCode记录随机产生的验证码
        final StringBuilder randomCode = new StringBuilder();
        // 随机产生codeCount个字符的验证码
        for (int i = 0; i < codeCount; i++) {
            final String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
            // 产生随机的颜色值，让输出的每个字符的颜色值都将不同
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);
            g.setColor(new Color(red, green, blue));
            g.drawString(strRand, (i + 1) * x, codeY);
            // 将产生的四个随机数组合在一起
            randomCode.append(strRand);
        }
        code = randomCode.toString();
    }

    public String writeToBase64() {
        try (final ByteArrayOutputStream sos = new ByteArrayOutputStream()) {
            ImageIO.write(bufferedImage, "png", sos);
            return Base64.getEncoder().encodeToString(sos.toByteArray());
        } catch (IOException e) {
            log.error("writeToBase64 error", e);
            return null;
        }
    }

    public String getCode() {
        return code;
    }
}
